import React, { useState, useMemo } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from "@/components/ui/scroll-area";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Search, BookOpen, Check } from 'lucide-react';

export default function StandardImportModal({ isOpen, onClose, onImport, availableStandards = [] }) {
  const [selectedStandards, setSelectedStandards] = useState(new Set());
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('all');

  // 筛选标准
  const filteredStandards = useMemo(() => {
    return availableStandards.filter(standard => {
      if (!standard) return false;
      const matchesSearch = searchTerm === '' || 
        (standard.name && standard.name.toLowerCase().includes(searchTerm.toLowerCase())) ||
        (standard.code && standard.code.toLowerCase().includes(searchTerm.toLowerCase())) ||
        (standard.description && standard.description.toLowerCase().includes(searchTerm.toLowerCase()));
      
      const matchesCategory = categoryFilter === 'all' || standard.category === categoryFilter;
      
      return matchesSearch && matchesCategory;
    });
  }, [availableStandards, searchTerm, categoryFilter]);

  // 获取可用的标准类别
  const categories = useMemo(() => {
    const categorySet = new Set();
    availableStandards.forEach(standard => {
      if (standard?.category) {
        categorySet.add(standard.category);
      }
    });
    return Array.from(categorySet);
  }, [availableStandards]);

  const handleToggleStandard = (standardId) => {
    if (!standardId) return;
    
    setSelectedStandards(prev => {
      const newSet = new Set(prev);
      if (newSet.has(standardId)) {
        newSet.delete(standardId);
      } else {
        newSet.add(standardId);
      }
      return newSet;
    });
  };

  const handleSelectAll = () => {
    const allFilteredIds = filteredStandards.map(s => s.id).filter(id => id);
    setSelectedStandards(new Set(allFilteredIds));
  };

  const handleClearAll = () => {
    setSelectedStandards(new Set());
  };

  const handleConfirmImport = () => {
    const standardsToImport = availableStandards.filter(standard => 
      standard && standard.id && selectedStandards.has(standard.id)
    );
    
    if (standardsToImport.length > 0) {
      onImport(standardsToImport);
    }
    handleClose();
  };

  const handleClose = () => {
    setSelectedStandards(new Set());
    setSearchTerm('');
    setCategoryFilter('all');
    onClose();
  };

  const categoryLabels = {
    'national': '国家标准',
    'industry': '行业标准', 
    'local': '地方标准',
    'enterprise': '企业标准'
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-4xl h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <BookOpen className="w-5 h-5 text-blue-600" />
            从知识库选择标准规范
          </DialogTitle>
          <DialogDescription>
            选择需要引用的标准规范作为编制依据。已选择 {selectedStandards.size} 项。
          </DialogDescription>
        </DialogHeader>

        {/* 筛选控件 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg">
          <div>
            <Label htmlFor="search">搜索标准</Label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
              <Input
                id="search"
                placeholder="输入标准名称或编号..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          
          <div>
            <Label htmlFor="category">标准类别</Label>
            <Select value={categoryFilter} onValueChange={setCategoryFilter}>
              <SelectTrigger>
                <SelectValue placeholder="选择标准类别" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类别</SelectItem>
                {categories.map(category => (
                  <SelectItem key={category} value={category}>
                    {categoryLabels[category] || category}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        {/* 批量操作 */}
        <div className="flex items-center justify-between px-4 py-2 bg-blue-50 rounded-lg">
          <span className="text-sm text-blue-700">
            显示 {filteredStandards.length} 项标准，已选择 {selectedStandards.size} 项
          </span>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={handleSelectAll}
              disabled={filteredStandards.length === 0}
            >
              全选当前
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleClearAll}
              disabled={selectedStandards.size === 0}
            >
              清空选择
            </Button>
          </div>
        </div>

        {/* 标准列表 */}
        <div className="flex-1 min-h-0">
          <ScrollArea className="h-full border rounded-lg">
            <div className="p-4 space-y-3">
              {filteredStandards.length > 0 ? (
                filteredStandards.map((standard) => (
                  <Card
                    key={standard.id}
                    className={`cursor-pointer transition-all duration-200 ${
                      selectedStandards.has(standard.id)
                        ? 'ring-2 ring-blue-500 bg-blue-50'
                        : 'hover:bg-gray-50'
                    }`}
                    onClick={() => handleToggleStandard(standard.id)}
                  >
                    <CardHeader className="p-4">
                      <div className="flex items-start gap-3">
                        <Checkbox
                          checked={selectedStandards.has(standard.id)}
                          onCheckedChange={() => handleToggleStandard(standard.id)}
                          className="mt-1"
                        />
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <h4 className="font-medium text-gray-900">
                              {standard.name}
                            </h4>
                            {standard.code && (
                              <Badge variant="outline" className="text-xs">
                                {standard.code}
                              </Badge>
                            )}
                            {standard.category && (
                              <Badge 
                                variant="secondary" 
                                className={`text-xs ${
                                  standard.category === 'national' ? 'bg-red-100 text-red-800' :
                                  standard.category === 'industry' ? 'bg-blue-100 text-blue-800' :
                                  standard.category === 'local' ? 'bg-green-100 text-green-800' :
                                  'bg-gray-100 text-gray-800'
                                }`}
                              >
                                {categoryLabels[standard.category] || standard.category}
                              </Badge>
                            )}
                          </div>
                          {standard.description && (
                            <p className="text-sm text-gray-600 mb-2">
                              {standard.description}
                            </p>
                          )}
                          <div className="flex items-center gap-4 text-xs text-gray-500">
                            {standard.publication_year && (
                              <span>发布年份: {standard.publication_year}</span>
                            )}
                            {standard.issuing_authority && (
                              <span>发布单位: {standard.issuing_authority}</span>
                            )}
                            {standard.status && (
                              <Badge 
                                variant={standard.status === 'active' ? 'default' : 'secondary'}
                                className="text-xs"
                              >
                                {standard.status === 'active' ? '现行' : 
                                 standard.status === 'superseded' ? '被替代' : '废止'}
                              </Badge>
                            )}
                          </div>
                        </div>
                      </div>
                    </CardHeader>
                  </Card>
                ))
              ) : (
                <div className="text-center py-12">
                  <BookOpen className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                  <p className="text-gray-500">未找到匹配的标准规范</p>
                  <p className="text-sm text-gray-400 mt-1">尝试调整搜索条件或筛选器</p>
                </div>
              )}
            </div>
          </ScrollArea>
        </div>

        <DialogFooter className="mt-4">
          <div className="flex items-center gap-4 w-full">
            <div className="flex-1 text-sm text-gray-600">
              已选择 {selectedStandards.size} 个标准规范
            </div>
            <Button variant="outline" onClick={handleClose}>
              取消
            </Button>
            <Button 
              onClick={handleConfirmImport}
              disabled={selectedStandards.size === 0}
            >
              <Check className="w-4 h-4 mr-2" />
              导入选择的标准 ({selectedStandards.size})
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}